﻿using System;
using System.Linq;

using Infrastructure.Diagnostics;
using TempEmployees.DAL;
using TempEmployees.BLL.EntitiesExtensions;

namespace TempEmployees.Web
{
    public partial class WebFormNewAssignment : ABasePage
    {
        protected override void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);

            Page.Form.DefaultButton = ButtonSubmit.UniqueID;  
        }

        protected void Page_LoadComplete(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                EmployeeDetails1.IsNewAssignment = true;
                AssignmentDetails1.SetStatusVisibility(false);
            }
            if (APageData.Exist<ExtendAssignmentData>())
            {
                ExtendAssignmentData data = APageData.Get<ExtendAssignmentData>();
                EmployeeDetails1.SetEmployeeID(DbServices.db.Assignments.First(a => a.ID == data.AssignmentID).Employee.ID);
                AssignmentDetails1.FillAssignmentDetails(data.AssignmentID);
                data.Remove();
            }
        }

        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            try
            {
                ErrorPanel.Visible = false;
                Logger.Debug("Adding new assignment");

                Employee newEmployee = EmployeeDetails1.NewAssignmentEmployee();
                if (newEmployee == null) return; //throw new BreakFlowException("New employee is null");

                // insert employee to the DB
                if (!EEmployee.InsertEmployee(newEmployee)) throw new Exception("Failed to insert employe to the DB");

                // try to create assignment (doesn't insert to the DB)
                Assignment newAssignment = AssignmentDetails1.CreateAssignment(newEmployee.ID);
                if (newAssignment == null) return; //throw new BreakFlowException("New assignment is null");

                if (!newAssignment.Insert()) throw new Exception("Failed to insert assignment to the DB");

                if (AssignmentDetails1.CommentText.Length > 0) EAssignment.InsertComment(newAssignment.ID, State.UserId, AssignmentDetails1.CommentText); ;

                APageData.Set(new UpdatedAssignmentData(newAssignment.ID, UpdatedAssignmentData.eUpdateType.New));
                Response.Redirect(GUIServices.PAGE_SEARCH_ASSIGNMENTS);
            }
            catch (Exception ex)
            {
                ErrorPanel.Visible = true;
                LabelError.Text = string.Format("{0}, check system log", ex.Message);
            }
        }     
    }

    public class ExtendAssignmentData : APageData
    {
        public int AssignmentID { get; private set; }

        public ExtendAssignmentData(int assignmentId)
        {
            AssignmentID = assignmentId;
        }
    }
}
